<template>
  <q-page class="page" style="min-width: 1200px; min-height: auto">
    <terminal-header :crane-id="selectedCraneId" :dark="dark" />

    <terminal-info
      :crane-data="craneData"
      :current-position="currentPosition"
      :dark="dark"
      :operateMode="operateMode"
      :orderSift="orderSift"
    />

    <terminal-main :crane-id="selectedCraneId" :is-terminal="isTerminal" :dark="dark" />

    <!-- <div style="height: 40px; width: 100%; border: 3px dashed #a7a3d6; margin-top: 60px">
      {{ craneAlarm }}
    </div> -->
  </q-page>
</template>

<script lang="ts">
import { useQuasar } from 'quasar';
import { computed, defineComponent, onMounted, ref, watch, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { api, get } from 'src/boot/api';
import { useEmitter } from 'src/emitter';
import { useYardStore } from 'src/stores/yard';
import { useWebsocket } from '../_sys/use-websocket1';
import TerminalMain from './main/index.vue';
import { CraneProps } from './main/models';
import TerminalHeader from './terminal-header/index.vue';
import TerminalInfo from './terminal-info/index.vue';
import { useTerminalStore } from './store';

export default defineComponent({
  name: 'terminal-crane',

  components: {
    TerminalHeader,
    TerminalInfo,
    TerminalMain,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();
    const $q = useQuasar();
    const operateMode = ref('2');
    const orderSift = ref<any[]>([]);

    const connected = ref(0);
    const oldConnected = ref();
    const craneAlarm = ref();

    const craneData = ref<CraneProps>({
      xAct: 0,
      yAct: 0,
      isEmpty: '',
      executeNumber: '',
      network: true,
    });

    const currentPosition = ref();

    const yard = useYardStore();
    const crnae = useTerminalStore();
    const { craneIds } = yard;
    const dark = ref(true);
    watchEffect(() => {
      $q.dark.set(dark.value);
    });

    const selectedCraneId = ref('');

    watchEffect(() => {
      const craneId = (route.query['crane-id'] ?? craneIds[0]) as string;
      if (!craneIds.includes(craneId)) {
        router.replace('/404');
        $q.notify({ message: '行车号不合法', color: 'negative', timeout: 0 });
        return;
      }
      if (craneId) {
        selectedCraneId.value = craneId;
      }
    });

    const isTerminal = computed(() => route.query['is-terminal'] !== undefined);

    document.addEventListener('keydown', async (event: any) => {
      const key = event.key;

      // 执行根据按键进行的操作
      switch (key) {
        case 'ArrowUp':
          await api.post('/move', { type: 3, craneNo: '01' });
          break;
        case 'ArrowDown':
          await api.post('/move', { type: 4, craneNo: '01' });
          break;
        case 'ArrowLeft':
          await api.post('/move', { type: 2, craneNo: '01' });
          break;
        case 'ArrowRight':
          await api.post('/move', { type: 1, craneNo: '01' });
          break;
        case 'Shift':
          await api.post('/liftMat', { craneNo: '01' });
          break;
        case 'Enter':
          await api.post('/unloadMat', { craneNo: '01' });
          break;
        default:
          console.log(`用户按下了按键: ${key}`);
      }
    });

    onMounted(async () => {
      const { data, code, message } = await get('CLTSOptions?craneNo=01');
      if (code === 200) {
        operateMode.value = data.craneOperateMode;
        orderSift.value = data.OrderTypeFilter;
        crnae.orderTypeName = data.OrderTypeName;
      } else {
        $q.notify({ message: message, color: 'negative', timeout: 1000 });
      }
    });

    // onMounted(() => {
    //   setInterval(() => {
    //     connected.value = Math.floor(Math.random() * 10); // 假设这里的值是随机生成的
    //   }, 2000);
    // });

    useEmitter('inform', payload => {
      if (payload.name !== 'terminal-crane-change-dark-mode') {
        return;
      }
      dark.value = payload.value;
    });

    const connected111 = () => {
      connected.value++;
    };

    useWebsocket('CRANE_WEBSOCKET,CRANE_INDEX_EQU_STOCK,CRANE_OPERATE_MODE', payload => {
      if (
        payload.topic !== 'CRANE_WEBSOCKET' &&
        payload.topic !== 'CRANE_INDEX_EQU_STOCK' &&
        payload.topic !== 'CRANE_OPERATE_MODE'
      ) {
        return;
      }

      if (payload.topic === 'CRANE_WEBSOCKET') {
        Object.keys(payload.data).forEach(ele => {
          try {
            const { craneNo } = payload.data[ele];
            if (craneNo == '1') {
              craneData.value.xAct = Number(payload.data[ele].xAct);
              craneData.value.yAct = Number(payload.data[ele].yAct);
              craneData.value.isEmpty = payload.data[ele].isEmpty;
              craneData.value.executeNumber = payload.data[ele].isEmpty;
              connected.value = payload.data[ele].reserve1;
              craneAlarm.value = payload.data[ele].errMsg1;

              // craneData.value.network = connected.value != oldConnected.value;
              // setTimeout(() => {
              //   console.log(connected.value, oldConnected.value);
              //  ;
              // }, 2000);
            }
          } catch (error: any) {
            console.log(error);
          }
        });
      }

      if (payload.topic === 'CRANE_INDEX_EQU_STOCK') {
        currentPosition.value = null;
        console.log('CRANE_INDEX_EQU_STOCK', payload.data[1]);
        currentPosition.value = payload.data[1];
        // const propertyCount = Object.keys(payload.data).length;
        // if (propertyCount === 1) {
        //   Object.keys(payload.data).forEach(ele => {
        //     currentPosition.value = payload.data[ele].stockNo;
        //   });
        // }
      }

      if (payload.topic === 'CRANE_OPERATE_MODE') {
        Object.keys(payload.data).forEach(ele => {
          try {
            operateMode.value = payload.data['01'];
          } catch (error: any) {
            console.log(error);
          }
        });
      }
    });

    setInterval(() => {
      craneData.value.network = connected.value != oldConnected.value;

      oldConnected.value = connected.value; // 更新prevValue为当前值
    }, 2500);

    // watch(connected, (newVal, oldVal) => {
    //   oldConnected.value = oldVal;
    // });

    // watchEffect(() => {
    //   if (connected.value === oldConnected.value) {
    //     console.log('值没有改变');
    //   } else {
    //     console.log('值发生了改变');
    //   }
    // });

    return {
      craneIds,
      path: route.path,
      selectedCraneId,
      isTerminal,
      dark,
      craneData,
      currentPosition,
      operateMode,
      orderSift,
      craneAlarm,
      connected111,
    };
  },
});
</script>
